<template>
  <div class="slot-management">
    <div class="page-header">
      <h2>面试时段管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <i class="el-icon-plus"></i> 新建时段
        </el-button>
        <el-button type="success" @click="handleBatchCreate">
          <i class="el-icon-files"></i> 批量创建
        </el-button>
      </div>
    </div>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="招聘ID" prop="recruitmentId">
        <el-input v-model="queryParams.recruitmentId" placeholder="请输入招聘ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="slotList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="时段ID" align="center" prop="slotId" />
      <el-table-column label="招聘ID" align="center" prop="recruitmentId" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template #default="{ row }">
          <span>{{ parseTime(row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template #default="{ row }">
          <span>{{ parseTime(row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地点" align="center" prop="location" :show-overflow-tooltip="true" />
      <el-table-column label="容量" align="center" prop="maxCapacity" width="100" />
      <el-table-column label="已预约" align="center" prop="bookedCount" width="100" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="{ row }">
          <el-tag :type="row.status === '0' ? 'success' : 'info'">{{ row.status === '0' ? '开放' : '关闭' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="260">
        <template #default="{ row }">
          <el-button size="small" type="text" icon="el-icon-edit" @click="handleUpdate(row)">修改</el-button>
          <el-button size="small" type="text" icon="el-icon-remove" @click="handleCapacity(row)">调整容量</el-button>
          <el-button v-if="row.status === '0'" size="small" type="text" icon="el-icon-video-pause" @click="handleClose(row)">关闭</el-button>
          <el-button v-else size="small" type="text" icon="el-icon-video-play" @click="handleReopen(row)">开放</el-button>
          <el-button size="small" type="text" icon="el-icon-delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 新建/编辑时段 -->
    <el-dialog :title="title" v-model="dialogVisible" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="招聘ID" prop="recruitmentId">
          <el-input v-model="form.recruitmentId" placeholder="请输入招聘ID" />
          <div class="el-form-item__help">请输入关联的招聘活动ID，时段ID将由系统自动生成</div>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入地点" />
        </el-form-item>
        <el-form-item label="容量" prop="maxCapacity">
          <el-input-number v-model="form.maxCapacity" :min="1" :max="200" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量创建 -->
    <el-dialog title="批量创建时段" :visible.sync="batchOpen" width="700px" append-to-body>
      <el-form ref="batchFormRef" :model="batchForm" :rules="batchRules" label-width="100px">
        <el-form-item label="招聘ID" prop="recruitmentId">
          <el-input v-model="batchForm.recruitmentId" placeholder="请输入招聘ID" />
        </el-form-item>
        <el-form-item label="模板日期" prop="templateDate">
          <el-date-picker
            v-model="batchForm.templateDate"
            type="date"
            placeholder="选择模板日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="时间段" prop="timeRange">
          <el-time-picker 
            is-range 
            range-separator="至" 
            start-placeholder="开始时间" 
            end-placeholder="结束时间" 
            v-model="batchForm.timeRange" 
            value-format="HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="复制天数">
          <el-input-number v-model="batchForm.repeatDays" :min="1" :max="30" />
        </el-form-item>
        <el-form-item label="地点" prop="location">
          <el-input v-model="batchForm.location" placeholder="请输入地点" />
        </el-form-item>
        <el-form-item label="容量" prop="maxCapacity">
          <el-input-number v-model="batchForm.maxCapacity" :min="1" :max="200" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatch">确 定</el-button>
        <el-button @click="batchOpen=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSlotsByClub, getInterviewSlot, addInterviewSlot, updateInterviewSlot, deleteInterviewSlot, createInterviewSlot, batchCreateInterviewSlots, updateSlotCapacity, closeInterviewSlot, reopenInterviewSlot } from '@/api/campus/club/interviewSlot'
import { getMyClubContext } from '@/api/campus/club/clubInfo'

export default {
  name: 'InterviewSlotManagement',
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      slotList: [],
      title: '',
      open: false,
      batchOpen: false,
      dialogVisible: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        recruitmentId: null
      },
      form: {},
      rules: {
        recruitmentId: [{ required: true, message: '招聘ID不能为空', trigger: 'blur' }],
        startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
        endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
        location: [{ required: true, message: '地点不能为空', trigger: 'blur' }],
        maxCapacity: [{ required: true, message: '容量不能为空', trigger: 'blur' }]
      },
      batchForm: {
        recruitmentId: null,
        templateDate: null,
        timeRange: [],
        repeatDays: 7,
        location: '',
        maxCapacity: 10
      },
      // 批量创建表单校验
      batchRules: {
        recruitmentId: [
          { required: true, message: '请输入招聘ID', trigger: 'blur' }
        ],
        templateDate: [
          { required: true, message: '请选择模板日期', trigger: 'change' }
        ],
        timeRange: [
          { required: true, message: '请选择时间段', trigger: 'change' }
        ],
        location: [
          { required: true, message: '请输入地点', trigger: 'blur' }
        ],
        maxCapacity: [
          { required: true, message: '请输入容量', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.loading = true
      const ctx = await getMyClubContext()
      const clubId = ctx?.data?.clubId
      
      // 检查clubId是否有效，避免调用API时出现null值
      if (!clubId) {
        // 如果clubId为null或无效，使用空列表
        this.slotList = []
        this.total = 0
        this.loading = false
        return
      }
      
      getSlotsByClub(clubId).then(res => {
        this.slotList = res.data || []
        this.total = this.slotList.length
        this.loading = false
      }).catch(() => {
        // API调用失败时使用空列表
        this.slotList = []
        this.total = 0
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.slotId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      // 先重置表单数据
      this.reset()
      // 设置标题
      this.title = '新建时段'
      // 立即设置dialogVisible为true打开对话框
      this.dialogVisible = true
    },
    handleUpdate(row) {
      // 先重置表单数据
      this.reset()
      const slotId = row.slotId || this.ids
      // 设置标题
      this.title = '修改时段'
      // 立即设置dialogVisible为true打开对话框
      this.dialogVisible = true
      
      // 加载数据
      if (slotId) {
        getInterviewSlot(slotId).then(res => {
          // 直接更新表单数据，对话框已打开
          if (res && res.data) {
            this.form = { ...res.data }
          }
        }).catch(err => {
          console.error('获取时段信息失败:', err)
        })
      }
    },
    handleCapacity(row) {
      this.$prompt('输入容量增减值（负数表示减少）', '调整容量', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^-?\d+$/,
        inputErrorMessage: '请输入整数'
      }).then(({ value }) => {
        return updateSlotCapacity(row.slotId, parseInt(value, 10))
      }).then(() => {
        this.$modal.msgSuccess('容量已调整')
        this.getList()
      }).catch(() => {})
    },
    handleClose(row) {
      this.$modal.confirm('确认关闭该时段？').then(() => closeInterviewSlot(row.slotId)).then(() => {
        this.$modal.msgSuccess('已关闭')
        this.getList()
      }).catch(() => {})
    },
    handleReopen(row) {
      this.$modal.confirm('确认重新开放该时段？').then(() => reopenInterviewSlot(row.slotId)).then(() => {
        this.$modal.msgSuccess('已开放')
        this.getList()
      }).catch(() => {})
    },
    handleDelete(row) {
      const slotIds = row.slotId || this.ids
      this.$modal.confirm('是否确认删除编号为"' + slotIds + '"的数据项？').then(() => deleteInterviewSlot(slotIds)).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    cancel() {
      // 关闭对话框
      this.dialogVisible = false
    },
    reset() {
      this.form = {
        slotId: null,
        recruitmentId: null,
        startTime: null,
        endTime: null,
        location: null,
        maxCapacity: 10,
        description: null
      }
      if (this.$refs['form'] && this.$refs['form'].resetFields) {
        try { this.$refs['form'].resetFields() } catch (e) {}
      }
    },
    submitForm() {
      this.$refs['form'].validate(async valid => {
        if (!valid) return
        const ctx = await getMyClubContext()
        const clubId = ctx?.data?.clubId
        
        if (!clubId) {
          this.$modal.msgError('获取社团信息失败')
          return
        }
        
        const formData = {
          ...this.form,
          clubId: clubId
        }
        
        const action = this.form.slotId ? updateInterviewSlot : createInterviewSlot
        action(formData).then(() => {
          this.$modal.msgSuccess(this.form.slotId ? '修改成功' : '创建成功')
          // 关闭对话框
          this.dialogVisible = false
          this.getList()
        }).catch(() => {
          this.$modal.msgError(this.form.slotId ? '修改失败' : '创建失败')
        })
      })
    },
    handleBatchCreate() {
      this.batchOpen = true
    },
    submitBatch() {
      this.$refs['batchFormRef'].validate(async valid => {
        if (!valid) return
        const ctx = await getMyClubContext()
        const clubId = ctx?.data?.clubId
        
        if (!clubId) {
          this.$modal.msgError('获取社团信息失败')
          return
        }
        
        const slots = []
        const [start, end] = this.batchForm.timeRange || []
        for (let i = 0; i < (this.batchForm.repeatDays || 1); i++) {
          const date = new Date(this.batchForm.templateDate)
          date.setDate(date.getDate() + i)
          const dateStr = `${date.getFullYear()}-${('0'+(date.getMonth()+1)).slice(-2)}-${('0'+date.getDate()).slice(-2)}`
          slots.push({
            clubId: clubId,
            recruitmentId: this.batchForm.recruitmentId,
            startTime: `${dateStr} ${start || '09:00:00'}`,
            endTime: `${dateStr} ${end || '10:00:00'}`,
            location: this.batchForm.location,
            maxCapacity: this.batchForm.maxCapacity,
            description: ''
          })
        }
        batchCreateInterviewSlots(slots).then(() => {
          this.$modal.msgSuccess('批量创建成功')
          this.batchOpen = false
          this.getList()
        }).catch(() => {
          this.$modal.msgError('批量创建失败')
        })
      })
    },
    parseTime(time) {
      if (!time) return ''
      return time.replace('T', ' ').substring(0, 16)
    }
  }
}
</script>

<style scoped>
.slot-management { padding: 20px; }
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.batch-operation {
  margin-bottom: 20px;
}

.batch-operation .el-button {
  margin-right: 10px;
}

.el-table .cell {
  padding: 0 10px;
}

.status-success {
  color: #67c23a;
}

.status-warning {
  color: #e6a23c;
}

.status-danger {
  color: #f56c6c;
}
</style>